package com.gitee.resouces;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author gcq
 * @Create 2022-07-03
 */
public class FileCopyTest {

    @Test
    public void copyFile() {
        /**
         * 1、创建输入\输出流
         * 2、执行文件拷贝、读取文件内容，写入到另一个文件中
         * 3、关闭文件资源
         */

        String originUrl = "lib/FileCopyTest.java";
        String targetUrl = "targetTest/target.txt";

        // 声明文件输入流、输出流
        FileInputStream originFileInputStream = null;
        FileOutputStream targetFileOutputStream = null;

        try {
            originFileInputStream = new FileInputStream(originUrl);
            targetFileOutputStream = new FileOutputStream(targetUrl);

            // 读取字节信息
            int content;
            // 读取写入字节
            while((content = originFileInputStream.read()) != -1) {
                targetFileOutputStream.write(content);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(originFileInputStream != null) {
                try {
                    originFileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(targetFileOutputStream != null) {
                try {
                    targetFileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}